package cm.just;

import cm.just.entry.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet",value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

//        User user = new User(userName,password);
        Connection connect =null;
        PreparedStatement preparedStatement = null;
        try {
            connect = JDBCUtil.getConnect();
            String sql = "select count(1) from t_user where username=? and password=?";//返回满足查询条件的结果个数，记录为个数，字段为count(1)
            preparedStatement = connect.prepareStatement(sql);
            preparedStatement.setString(1,userName);
            preparedStatement.setString(2,password);

            ResultSet resultSet = preparedStatement.executeQuery();
            String info = null;
            if(resultSet.next()){
//                int count = resultSet.getInt(1);
                int count = resultSet.getInt("count(1)");
                if(count>0){
                    info = "登录成功";
                }else{
                    info = "登录失败";
                }
            }
            response.setContentType("text/html;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            printWriter.print(info);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


}
